<?php

namespace App\Http\Controllers\AdminApi\User;

use App\Http\Controllers\Controller;
use App\Http\Models\Admin\ClassifyPermissions;
use App\Http\Models\Admin\Permission_;
use App\Http\Models\Admin\Role_;
use App\Http\Models\Admin\RolePermissions;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Spatie\Permission\Middlewares\RoleMiddleware;
use Illuminate\Support\Facades\DB;

class ClassifyController extends Controller
{
    //为选择框获取分类数据
    public function getClassify()
    {
        // redaySql();
        $result = ClassifyPermissions::with(['classifyHasMany'])->where([['parent_id', '=', '0']])->get();
        // showSql();
        return response()->json(['code' => 20000, 'message' => '角色选择查询成功', 'data' => $result]);
    }
    // 获取所有角色
    public function getClassifyPermissions()
    {
        $uid = Auth::guard('adminapi')->user()->id;
        $user = User::where(array('id' => $uid))->first();
        $userRolesId = $user->roles()->pluck('id')->toArray(0)[0];
        $role = Role_::find($userRolesId);
        // redaySql();
        $roles = Role_::with(['hasManyDetails']);
        if ($role->name != 'administrator') {
            $roles->where('name', '!=', 'administrator');
        }

        $roles = $roles->paginate(8);
        // showSql();
        // die;

        $Permissions = new Permission_();
        $Permissions = $Permissions->with(['hasDetails' => function ($query) {
            // $query->with(['hasManyDetails'=>function($qu_det){
            //     $qu_det->with('hasDetails');
            // }]);
        }])->get();
        $classify_per = new ClassifyPermissions();
        $classify = $classify_per->where(array('parent_id' => 0))->orderBy('rank', 'DESC')->with(['classifyHasMany' => function ($query) {
            $query->with(['hasManyDetails' => function ($qu_det) {
                $qu_det->with('hasDetails');
            }]);
        }])->get();
        return response()->json(['code' => 20000, 'message' => '角色查询成功', 'data' => compact('roles', 'Permissions', 'classify')]);
    }


    public function insertClassifyPermissions(Request $request)
    {
        $name = $request->get('name');
        // var_dump($name,$perList);die;
        // print_r ($perList[0]);die;
        $arr = [];
        if (empty($name)) {
            return response()->json(['code' => 20001, 'message' => '请输入角色名', 'data' => $name]);
        }
        $classifys = $request->get('classifys');
        $arr = [];
        //循环判断有哪些选中的权限配置
        foreach ($classifys as $i => $classify) {
            for ($s = 0; $s < sizeof($classify['classify_has_many']); $s++) {
                for ($j = 0; $j < sizeof($classifys[$i]['classify_has_many'][$s]['has_many_details']); $j++) {
                    if (array_key_exists('checked', $classifys[$i]['classify_has_many'][$s]['has_many_details'][$j])) {

                        if ($classifys[$i]['classify_has_many'][$s]['has_many_details'][$j]['checked'] == true) {

                            array_push($arr, $classifys[$i]['classify_has_many'][$s]['has_many_details'][$j]['has_details']['permission_id']);
                        }
                    }
                }
            }
        }
        $role = Role_::where(array('name' => $name))->get();
        if (!empty(count($role))) {
            return response()->json(['code' => 20001, 'message' => '此角色已存在', 'data' => $role]);
        }
        $array = [
            'name' => $name
        ];
        $inser_per = Role_::create($array);
        $ress = $inser_per->hasManyDetails()->attach($arr);
        return response()->json(['code' => 20000, 'message' => '角色添加成功', 'data' => $ress]);
    }

    //修改角色信息
    public function updateClassifyPermissions(Request $request)
    {
        $id = $request->get('id');
        $name = $request->get('name');
        $classifys = $request->get('classifys');
        $arr = [];
        //循环判断有哪些选中的权限配置
        foreach ($classifys as $i => $classify) {
            for ($s = 0; $s < sizeof($classify['classify_has_many']); $s++) {
                for ($j = 0; $j < sizeof($classifys[$i]['classify_has_many'][$s]['has_many_details']); $j++) {
                    if (array_key_exists('checked', $classifys[$i]['classify_has_many'][$s]['has_many_details'][$j])) {

                        if ($classifys[$i]['classify_has_many'][$s]['has_many_details'][$j]['checked'] == true) {

                            array_push($arr, $classifys[$i]['classify_has_many'][$s]['has_many_details'][$j]['has_details']['permission_id']);
                        }
                    }
                }
            }
        }
        // dd($arr);

        $array = [
            'name' => $name
        ];
        //获取id为$perId 的当前权限数据
        $role = Role_::findOrFail($id);
        //当当前输入的角色名和数据库的角色名匹配的时候 输出角色已存在
        if ($role->name !== $name) {
            $result = Role_::where(array('name' => $name))->get();
            if (!empty(count($result))) {
                return response()->json(['code' => 20001, 'message' => '此角色名已经存在,请重新输入', 'data' => $classifys]);
            }
        }
        // dd($role->id);die;
        $flag = RolePermissions::where('role_id', $role->id)->delete();
        //修改当前角色名称
        $role->update($array);
        //修改关联 角色名称表和 权限说明表的 id信息 
        $ress = $role->hasManyDetails()->syncWithoutDetaching($arr);
        // dd($ress);die;
        return response()->json(['code' => 20000, 'message' => '角色修改成功', 'data' => $ress]);
    }

    public function deleteClassifyPermissions(Request $request)
    {
        $id = $request->get('id');
        $role = Role_::findOrFail($id);
        $role->delete();
        $roles = RolePermissions::where('role_id', $id)->delete();
        return response()->json(['code' => 20000, 'message' => '删除成功', 'data' => $id]);
    }
}
